import strHtml from "./UserPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { userService } from "../../services/userService.js";

export class UserPage {
  constructor(userId) {
    this.users = [];
    this.selectedUser = null;
    this.initTable();
    this.initModal();
  }

  async loadUsers() {
    try {
      const response = await userService.listUsers();
      this.users = response?.data?.length ? response.data : [];
      this.renderTable();
    } catch (error) {
      console.error("加载用户失败:", error);
    }
  }

  initTable() {
    this.table = DomUtils.create("table", { className: "user-table" });
    this.table.innerHTML = `
      <thead>
        <tr>
          <th>ID</th>
          <th>姓名</th>
          <th>邮箱</th>
          <th>角色</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    `;
  }

  initModal() {
    this.modal = DomUtils.create("div", { className: "user-modal" });
    this.modal.innerHTML = `
      <div class="modal-content">
        <h3>用户表单</h3>
        <form id="userForm">
          <input type="hidden" id="userId">
          <div>
            <label>姓名:</label>
            <input type="text" id="name" required>
          </div>
          <div>
            <label>邮箱:</label>
            <input type="email" id="email" required>
          </div>
          <div>
            <label>角色:</label>
            <select id="role">
              <option value="user">用户</option>
              <option value="admin">管理员</option>
            </select>
          </div>
          <button type="submit">保存</button>
          <button type="button" class="cancel">取消</button>
        </form>
      </div>
    `;
  }

  renderTable() {
    const tbody = this.table.querySelector("tbody");
    tbody.innerHTML = this.users
      .map(
        (user) => `
      <tr>
        <td>${user.id}</td>
        <td>${user.name}</td>
        <td>${user.email}</td>
        <td>${user.role}</td>
        <td>
          <button class="edit" data-id="${user.id}">编辑</button>
          <button class="delete" data-id="${user.id}">删除</button>
        </td>
      </tr>
    `
      )
      .join("");

    this.bindTableEvents();
  }

  bindTableEvents() {
    this.table.querySelectorAll(".edit").forEach((btn) => {
      btn.addEventListener("click", () => this.handleEdit(btn.dataset.id));
    });

    this.table.querySelectorAll(".delete").forEach((btn) => {
      btn.addEventListener("click", () => this.handleDelete(btn.dataset.id));
    });
  }

  async handleEdit(userId) {
    this.selectedUser = this.users.find((u) => u.id == userId);
    DomUtils.show(this.modal);
    DomUtils.setValue("#userId", this.selectedUser.id);
    DomUtils.setValue("#name", this.selectedUser.name);
    DomUtils.setValue("#email", this.selectedUser.email);
    DomUtils.setValue("#role", this.selectedUser.role);
  }

  async handleDelete(userId) {
    if (confirm("确认删除该用户？")) {
      await userService.deleteUser(userId);
      await this.loadUsers();
    }
  }

  async render() {
    const container = DomUtils.create("div", { className: "user-container" });
    const header = DomUtils.create("div", { className: "table-header" });

    const addButton = DomUtils.create("button", {
      className: "add-user",
      textContent: "新增用户",
      onclick: () => {
        this.selectedUser = null;
        DomUtils.show(this.modal);
        DomUtils.resetForm("#userForm");
      },
    });

    header.appendChild(addButton);
    container.appendChild(header);
    container.appendChild(this.table);
    container.appendChild(this.modal);

    this.modal.querySelector("form").addEventListener("submit", async (e) => {
      e.preventDefault();
      const formData = {
        name: DomUtils.getValue("#name"),
        email: DomUtils.getValue("#email"),
        role: DomUtils.getValue("#role"),
      };

      try {
        if (this.selectedUser) {
          await userService.updateUser(DomUtils.getValue("#userId"), formData);
        } else {
          await userService.createUser(formData);
        }
        DomUtils.hide(this.modal);
        await this.loadUsers();
      } catch (error) {
        console.error("保存用户失败:", error);
      }
    });

    this.modal.querySelector(".cancel").addEventListener("click", () => {
      DomUtils.hide(this.modal);
    });

    await this.loadUsers();
    return container;
  }
}
